// send.js
var requester = require('../../common/requester.js');
var EventEmitter = require('../../common/EventEmitter.js');

Page({
    data: {
        curSelectedImageUrl: '',
        isAudit: true
    },

    onLoad: function (param) {
        this.from = param.from;
        this.setData({
            curSelectedImageUrl: param.url,
        });
    },

    // 选择图片
    chooseImages: function (e) {
        let me = this;
        wx.chooseImage({
            success: (res) => {
                console.log(res);
                let tempFilePath = res.tempFilePaths[0];
                me.setData({
                    curSelectedImageUrl: tempFilePath
                });
            }
        });
    },

    // 输入内容
    infoInput: function (e) {
        let inputContent = e.detail.value;
        let str = inputContent.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
        this.setData({
            infoContent: str
        })
    },

    //Upload image
    uploadImage: function (e) {
        let me = this;
        let imageUrl = me.data.curSelectedImageUrl;
        if (!imageUrl) {
            //Toast
            wx.showToast({
                title: '请选择一张图片',
                icon: 'warn',
                duration: 2000
            });
            return;
        }

        let reqObj = {
            url: requester.service.uploadFile,
            formData: {
                textInfo: me.data.infoContent || '',
            },
            filePath: imageUrl,
            name: 'picFile'
        };

        wx.showLoading({
            title: '正在上传...',
            mask: true
        });
        requester.uploadFile(reqObj)
            .then((res) => {
                console.log("uploadFile-success", res);
                wx.hideLoading();
                wx.showToast({
                    title: '上传成功',
                    icon: 'success',
                    duration: 3000,
                    mask: true
                });
                setTimeout(() => {
                    wx.hideToast();
                    me.backToPrePage();
                }, 1700);
            })
            .catch(err => {
                wx.showToast({
                    title: '上传失败',
                    icon: 'warning',
                    duration: 2000,
                    mask: true
                })
            });
    },

    backToPrePage: function () {
        let me = this;
        EventEmitter.dispatch('backFormSend');
        wx.navigateBack({
            url: me.from === 'main' ? '../index/index' : '../me/me'
        });
    }
});